using System;
using System.Collections.Generic;
using BLToolkit.Data;
using BLToolkit.Data.Linq;
using dbvc.data;
using System.Linq;

namespace dbvc.Queries
{
    public class ScriptQuery
    {
        private static readonly Func<DAA, int[], IQueryable<db_version_script>> cGetVersionScripts = CompiledQuery.Compile((DAA db, int[] vers) =>
            db.GetTable<db_version_script>().Where(vs => vers.Contains(vs.id_version)));

        private static readonly Func<DAA, int[], IQueryable<db_script>> cGetScripts = CompiledQuery.Compile((DAA db, int[] vers) =>
            db.GetTable<db_version_script>().Where(vs => vers.Contains(vs.id_version)).OrderBy(x => x.id_version)
              .Join(db.GetTable<db_script>(),  x=>x.id_script,  x => x.id, (vs, s) => s));

        public static List<db_script> GetScripts(int[] ver_ids)
        {
            using( var db = new DAA() ){
                return cGetScripts(db, ver_ids).ToList();
            }
        }

        public static List<db_version_script> GetVersionScripts(int[] ver_ids)
        {
            using (var db = new DAA()){
                return cGetVersionScripts(db, ver_ids).ToList();
            }
        }

        public static string GetScriptText(int id)
        {
            using (var db = new DAA())
            {
                var item =  db.GetTable<db_script>().Where(s => s.id == id).FirstOrDefault();
                return item == null ? string.Empty : item.text;
            }
        }
    }
}